<?php

namespace app\kaoqin\api;

use app\common\logic\FullUser;
use app\common\logic\OldRecord;
use app\common\logic\RecordSumToday;

class Me extends Common
{
    /**
     * 我的考勤首页
     * @author wb <pithyone@vip.qq.com>
     */
    public function index()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $user_id = getUid();
        $time = date('Y-m-d');

        if (isset($req['u']) && !empty($req['u']))
            $user_id = $req['u'];

        if (isset($req['t']) && !empty($req['t']))
            $time = date('Y-m-d', strtotime($req['t']));

        //返回用户信息
        $ret = FullUser::getUserById($user_id);
        if ($ret === false)
            return $this->error('个人信息获取失败');

        //返回当天打卡记录
        $work_log = OldRecord::getWorkLog($user_id, $time);
        foreach ($work_log as $k => $v) {
            if ($k % 2 == 0) {
                $work_log[$k]['status'] = 'come';
                $work_log[$k]['time_diff'] = 0;
            } else {
                $work_log[$k]['status'] = 'leave';
                $work_log[$k]['time_diff'] = time_diff2hour($v['time_unix'] - $work_log[$k - 1]['time_unix']);
            }
        }
        $ret['work_log'] = $work_log;

        //返回到岗时间&工作时长
        if (count($work_log) > 0) {
            $first_work_time = $work_log[0]['time'];
            $ret['first_time'] = $first_work_time;

            $work_time_total = $this->getWorkTime($time, $work_log);
            $ret['total_time'] = $work_time_total;
        } else {
            $ret['first_time'] = "尚未签到";
            $ret['total_time'] = 0;
        }

        //返回工作状态
        if ($time == date('Y-m-d', time())) {
            $recordSumToday = RecordSumToday::get(['id' => $user_id]);
            $status = '';

            if ($recordSumToday['count'] == 0) $status = 'xiujia';
            else {
                if ($recordSumToday['count'] % 2 == 0) $status = 'xiuxi';
                else if ($recordSumToday['count'] % 2 == 1) {
                    if (!empty($recordSumToday['extattr'])) {
                        $extattr = unserialize($recordSumToday['extattr']);
                        if (!isset($extattr['attrs']) || empty($extattr['attrs'])) {
                            $status = 'working';
                        } else {
                            foreach ($extattr['attrs'] as $val) {
                                if ($val['name'] == '身份' && $val['value'] == '学生') $status = 'learning';
                            }
                        }
                    } else $status = 'working';
                }
            }

            $ret['work_status'] = $status;
            $ret['work_count'] = '';
        } else {
            $ret['work_status'] = '';
            $ret['work_count'] = count($work_log) > 0 ? (count($work_log) % 2 == 0 ? 'ok' : 'error') : '';
        }

        $days = [];
        $week_array = ["日", "一", "二", "三", "四", "五", "六"];

        for ($i = 6; $i >= 0; $i--) {
            $d = '-' . $i . ' day';
            $desc = date('Y年m月d日', strtotime($d));
            $simple = date('Ymd', strtotime($d));
            $day = date('d', strtotime($d));
            $week = $week_array[date("w", strtotime($d))];

            if ($simple == date('Ymd')) {
                $status = '';
            } else {
                $time_diff = [strtotime(date('Y-m-d 00:00:00', strtotime($d))), strtotime(date('Y-m-d 23:59:59', strtotime($d)))];
                $count = OldRecord::where(['userId' => $user_id, 'time' => ['between', $time_diff]])->count();
                $status = empty($count) ? '' : ($count % 2 == 0 ? 'ok' : 'error');
            }

            $days[] = ['desc' => $desc, 'simple' => $simple, 'day' => $day, 'week' => $week, 'status' => $status];
        }

        $ret['days'] = $days;

        return $this->success($ret);
    }

    public function work()
    {
        if (!$this->checkAuth())
            return $this->_error;

        $req = input('');
        $user_id = getUid();

        if (isset($req['u']) && !empty($req['u']))
            $user_id = $req['u'];

        if (!isset($req['t']) && empty($req['t'])) $time = 'month';
        else $time = $req['t'];

        if (!isset($req['tag']) && empty($req['tag'])) $tag = 'count';
        else $tag = $req['hour'];

        if ($time == 'week')
            $start_time = mktime(0, 0, 0, date("m"), date("d") - date("w") + 1, date("Y"));
        else
            $start_time = mktime(0, 0, 0, date("m"), 1, date("Y"));

        $end_time = strtotime(date('Y-m-d 23:59:59'));

        $time_diff = [$start_time, $end_time];
        $records = OldRecord::getRecordByUidANDTime($user_id, $time_diff);

        $day_come = 0;
        $come_count = 0;
        $work_time = 0;
        $work_log = [];

        foreach ($records as $record) {
            $day_come++;
            $log = explode(',', $record['log']);
            $come_count += count($log);
            $work_time += $this->getWorkHour($record['log']);

            $time = $record['time'];
            if ($time == date('Y-m-d')) {
                $time = '今天';
            } else {
                $time = date('m-d', strtotime($time)) . ' ' . get_week($time);
            }

            $temp = [];
            foreach ($log as $k => $v) {
                $t = date('H:i:s', $v);

                if ($k % 2 == 0) {
                    $status = 'come';
                    $time_diff = 0;
                } else {
                    $status = 'leave';
                    $time_diff = time_diff2hour($v - $log[$k - 1]);
                }
                $temp[count($log) - 1 - $k] = ['time' => $t, 'status' => $status, 'time_diff' => $time_diff];
            }

            $work_log[$time][] = $temp;
        }

        $ret['day_come'] = $day_come;
        $ret['come_count'] = $come_count;
        $ret['work_time'] = time_diff2hour($work_time);
        $ret['work_log'] = $work_log;

        return $ret;
    }

    /**
     * 根据打卡记录返回工作时长
     * @param $log
     * @return int
     * @author wb <pithyone@vip.qq.com>
     */
    private function getWorkHour($log)
    {
        $work_log = explode(',', $log);
        if (!is_array($work_log)) return 0;    //非数组
        if (count($work_log) < 1) return 0;    //数组为空

        $time_diff = 0;
        $odd = array();
        $even = array();

        foreach ($work_log as $k => $v) {
            if ($k % 2 == 0) $odd[] = $v;
            else $even[] = $v;
        }

        foreach ($odd as $k => $v) {
            if (!empty($even[$k])) {
                $time_diff += ($even[$k] - $odd[$k]);
            }
        }

        return $time_diff;
    }


    /**
     * 根据日期和打卡记录返回工作时长
     * @param $time
     * @param $work_log
     * @return string
     * @author wb <pithyone@vip.qq.com>
     */
    private function getWorkTime($time, $work_log)
    {
        $time_diff = 0;
        $odd = array();
        $even = array();

        foreach ($work_log as $k => $v) {
            if ($k % 2 == 0) $odd[] = $v;
            else $even[] = $v;
        }

        foreach ($odd as $k => $v) {
            if (!empty($even[$k])) {
                $time_diff += ($even[$k]['time_unix'] - $odd[$k]['time_unix']);
            } else {
                $today = date('Y-m-d', time());
                if ($time == $today)
                    $time_diff += (time() - $odd[$k]['time_unix']);
                else {
//                    TODO: 非当天&奇数打卡->操作
//                    $time_end = date('Y-m-d 23:59:59', strtotime($time));
//                    $time_diff += (strtotime($time_end) - $odd[$k]['time_unix']);
                }
            }
        }


        return $time_diff ? time_diff2string($time_diff) : $time_diff;
    }
}